﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using MyCompany.MyProject.Common;
using MyCompany.MyProject.Common.DB;
using MyCompany.MyProject.Extensions.Auth;
using System.IdentityModel.Tokens.Jwt;
using System.Text;

namespace MyCompany.MyProject.Extensions.ServiceExtensions;

public static class Authentication_JWTSetup
{
    public static void AddAuthentication_JWTSetup(this IServiceCollection services)
    {
        if(services == null) throw new ArgumentNullException(nameof(services));

        var symmetricKeyAsBase64 = AppSecretConfig.Audience_Secret_String;
        var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
        var signingKey =    new SymmetricSecurityKey(keyByteArray);
        var Issuer = AppSettings.app(new string[] { "TokenParms", "Issuer" });
        var Audience = AppSettings.app(new string[] { "TokenParms", "Audience" });
        var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

        // 令牌验证参数
        var tokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = signingKey,
            ValidateIssuer = true,
            ValidIssuer = Issuer,
            ValidateAudience = true,
            ValidAudience = Audience,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero,//TimeSpan.FromSeconds(30),
            RequireExpirationTime = true,

            //NameClaimType = "name",
            //RoleClaimType="role"
        };

        // 开启 Bearer 认证
        services.AddAuthentication(o =>
        {
            o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            o.DefaultChallengeScheme = nameof(ApiResponseHandler);
            o.DefaultForbidScheme = nameof(ApiResponseHandler);
        })
            .AddJwtBearer(o =>
            {
                o.TokenValidationParameters = tokenValidationParameters;
                o.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/api/chathub")))
                        {
                            context.Token = accessToken;
                        }
                        return Task.CompletedTask;
                    },
                    OnChallenge = context =>
                    {
                        context.Response.Headers["Token-Error"] = context.ErrorDescription;
                        return Task.CompletedTask;
                    },
                    OnAuthenticationFailed = context =>
                    {
                        var jwtHandler = new JwtSecurityTokenHandler();
                        var token = context.Request.Headers["Authentication"].ObjToString().Replace("Bearer ", ""); ;
                        if (token.IsNotEmptyOrNull() && jwtHandler.CanReadToken(token))
                        {
                            var jwtToken = jwtHandler.ReadJwtToken(token);
                            if (jwtToken.Issuer != Issuer)
                            {
                                context.Response.Headers["Token-Error-Iss"] = "issuer is wrong";
                            }
                            if (jwtToken.Audiences.FirstOrDefault() != Audience)
                            {
                                context.Response.Headers["Token-Error-Aud"] = "Audience is wrong";
                            }
                        }

                        // 如果过期，则把<是否过期>添加到返回头信息中
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers["Token-Expired"] = "true";
                        }
                        return Task.CompletedTask;
                    }
                };
            })
            .AddScheme<AuthenticationSchemeOptions, ApiResponseHandler>(nameof(ApiResponseHandler), o => { });

        //services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
        //{
        //    options.TokenValidationParameters.NameClaimType = "name";
        //    options.TokenValidationParameters.RoleClaimType = "role";
        //});
    }
}
